import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Checkbox } from '@/components/ui/checkbox'
import { Stethoscope, Eye, EyeOff, Mail, Lock, User, Phone } from 'lucide-react'
import { useToast } from '@/hooks/use-toast'
import { useAuth } from '@/contexts/auth-context'
import { AuthAPI } from '@/services/api'

export default function LoginPage() {
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [verificationCode, setVerificationCode] = useState('')
  const [isGettingCode, setIsGettingCode] = useState(false)
  const navigate = useNavigate()
  const { toast } = useToast()
  const { login } = useAuth()

  const [loginForm, setLoginForm] = useState({
    username: '',
    password: '',
    remember: false
  })

  const [registerForm, setRegisterForm] = useState({
    username: '',
    name: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: ''
  })

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)

    try {
      const response = await AuthAPI.login({
        username: loginForm.username,
        password: loginForm.password
      })

      if (response.code === 0 && response.data) {
        // 登录成功，保存token和用户信息
        console.log('Login response:', response.data) // 调试日志
        
        // 立即调用login函数更新状态
        login(response.data.token, response.data.user)
        
        toast({
          title: "登录成功",
          description: "欢迎回到灵溪医疗助手智能体平台！",
        })
        
        // 延迟导航，确保状态更新完成
        setTimeout(() => {
          navigate('/')
        }, 100)
      } else {
        toast({
          title: "登录失败",
          description: response.message || "账号或密码错误",
          variant: "destructive"
        })
      }
    } catch (error) {
      console.error('Login error:', error)
      toast({
        title: "登录失败",
        description: error instanceof Error ? error.message : "网络错误，请稍后重试",
        variant: "destructive"
      })
    } finally {
      setIsLoading(false)
    }
  }

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)

    try {
      // 验证密码一致性
      if (registerForm.password !== registerForm.confirmPassword) {
        toast({
          title: "注册失败",
          description: "两次输入的密码不一致",
          variant: "destructive"
        })
        setIsLoading(false)
        return
      }

      // 验证必填字段
      if (!registerForm.username || !registerForm.name || !registerForm.email || !registerForm.password || !verificationCode) {
        toast({
          title: "注册失败",
          description: "请填写完整的注册信息",
          variant: "destructive"
        })
        setIsLoading(false)
        return
      }

      const response = await AuthAPI.register({
        username: registerForm.username,
        password: registerForm.password,
        confirmPassword: registerForm.confirmPassword,
        remark: registerForm.name, // 使用姓名作为备注
        email: registerForm.email,
        code: verificationCode
      })

      if (response.code === 0) {
        toast({
          title: "注册成功",
          description: "注册成功，请使用账号密码登录！",
        })
        
        // 清空注册表单
        setRegisterForm({
          username: '',
          name: '',
          email: '',
          phone: '',
          password: '',
          confirmPassword: ''
        })
        setVerificationCode('')
        
        // 切换到登录标签
        // 这里可以通过设置一个状态来控制标签切换
      } else {
        toast({
          title: "注册失败",
          description: response.message || "注册失败，请检查信息后重试",
          variant: "destructive"
        })
      }
    } catch (error) {
      console.error('Register error:', error)
      toast({
        title: "注册失败",
        description: error instanceof Error ? error.message : "网络错误，请稍后重试",
        variant: "destructive"
      })
    } finally {
      setIsLoading(false)
    }
  }

  const handleGetVerificationCode = async () => {
    if (!registerForm.email) {
      toast({
        title: "获取验证码失败",
        description: "请先输入邮箱地址",
        variant: "destructive"
      })
      return
    }

    setIsGettingCode(true)
    try {
      const response = await AuthAPI.getCode(registerForm.email)
      
      if (response.code === 0) {
        toast({
          title: "验证码已发送",
          description: "请查收邮箱中的验证码",
        })
      } else {
        toast({
          title: "获取验证码失败",
          description: response.message || "发送失败，请稍后重试",
          variant: "destructive"
        })
      }
    } catch (error) {
      console.error('Get code error:', error)
      toast({
        title: "获取验证码失败",
        description: error instanceof Error ? error.message : "网络错误，请稍后重试",
        variant: "destructive"
      })
    } finally {
      setIsGettingCode(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-green-50 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo */}
        <div className="text-center mb-8">
          <Link to="/" className="inline-flex items-center space-x-2">
            <div className="w-12 h-12 bg-gradient-to-r from-blue-600 to-green-500 rounded-xl flex items-center justify-center">
              <Stethoscope className="w-6 h-6 text-white" />
            </div>
            <span className="text-2xl font-bold bg-gradient-to-r from-blue-600 to-green-500 bg-clip-text text-transparent">
              灵溪医疗助手
            </span>
          </Link>
          <p className="text-gray-600 mt-2">智能体平台</p>
        </div>

        <Card className="border-0 bg-white/80 backdrop-blur-sm shadow-xl">
          <CardHeader className="text-center pb-4">
            <CardTitle className="text-2xl">欢迎使用</CardTitle>
            <CardDescription>
              登录或注册以开始使用我们的智能医疗服务
            </CardDescription>
          </CardHeader>
          
          <CardContent>
            <Tabs defaultValue="login" className="w-full">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="login">登录</TabsTrigger>
                <TabsTrigger value="register">注册</TabsTrigger>
              </TabsList>
              
              {/* 登录表单 */}
              <TabsContent value="login">
                <form onSubmit={handleLogin} className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="username">账号</Label>
                    <div className="relative">
                      <User className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                      <Input
                        id="username"
                        type="text"
                        placeholder="请输入账号"
                        className="pl-10"
                        value={loginForm.username}
                        onChange={(e) => setLoginForm({...loginForm, username: e.target.value})}
                        required
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="password">密码</Label>
                    <div className="relative">
                      <Lock className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                      <Input
                        id="password"
                        type={showPassword ? "text" : "password"}
                        placeholder="请输入密码"
                        className="pl-10 pr-10"
                        value={loginForm.password}
                        onChange={(e) => setLoginForm({...loginForm, password: e.target.value})}
                        required
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                        onClick={() => setShowPassword(!showPassword)}
                      >
                        {showPassword ? (
                          <EyeOff className="h-4 w-4 text-gray-400" />
                        ) : (
                          <Eye className="h-4 w-4 text-gray-400" />
                        )}
                      </Button>
                    </div>
                  </div>
                  
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id="remember"
                        checked={loginForm.remember}
                        onCheckedChange={(checked) => 
                          setLoginForm({...loginForm, remember: checked as boolean})
                        }
                      />
                      <Label htmlFor="remember" className="text-sm">记住我</Label>
                    </div>
                    <Button variant="link" className="px-0 text-sm">
                      忘记密码？
                    </Button>
                  </div>
                  
                  <Button 
                    type="submit" 
                    className="w-full bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800"
                    disabled={isLoading}
                  >
                    {isLoading ? "登录中..." : "登录"}
                  </Button>
                </form>
              </TabsContent>
              
              {/* 注册表单 */}
              <TabsContent value="register">
                <form onSubmit={handleRegister} className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="reg-username">账号</Label>
                    <div className="relative">
                      <User className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                      <Input
                        id="reg-username"
                        type="text"
                        placeholder="请输入账号"
                        className="pl-10"
                        value={registerForm.username}
                        onChange={(e) => setRegisterForm({...registerForm, username: e.target.value})}
                        required
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="name">姓名</Label>
                    <div className="relative">
                      <User className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                      <Input
                        id="name"
                        type="text"
                        placeholder="请输入您的姓名"
                        className="pl-10"
                        value={registerForm.name}
                        onChange={(e) => setRegisterForm({...registerForm, name: e.target.value})}
                        required
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="reg-email">邮箱地址</Label>
                    <div className="relative">
                      <Mail className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                      <Input
                        id="reg-email"
                        type="email"
                        placeholder="请输入邮箱地址"
                        className="pl-10"
                        value={registerForm.email}
                        onChange={(e) => setRegisterForm({...registerForm, email: e.target.value})}
                        required
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="phone">手机号</Label>
                    <div className="relative">
                      <Phone className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                      <Input
                        id="phone"
                        type="tel"
                        placeholder="请输入手机号"
                        className="pl-10"
                        value={registerForm.phone}
                        onChange={(e) => setRegisterForm({...registerForm, phone: e.target.value})}
                        required
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="reg-password">密码</Label>
                    <div className="relative">
                      <Lock className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                      <Input
                        id="reg-password"
                        type={showPassword ? "text" : "password"}
                        placeholder="请输入密码"
                        className="pl-10 pr-10"
                        value={registerForm.password}
                        onChange={(e) => setRegisterForm({...registerForm, password: e.target.value})}
                        required
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                        onClick={() => setShowPassword(!showPassword)}
                      >
                        {showPassword ? (
                          <EyeOff className="h-4 w-4 text-gray-400" />
                        ) : (
                          <Eye className="h-4 w-4 text-gray-400" />
                        )}
                      </Button>
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="confirm-password">确认密码</Label>
                    <div className="relative">
                      <Lock className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                      <Input
                        id="confirm-password"
                        type={showPassword ? "text" : "password"}
                        placeholder="请再次输入密码"
                        className="pl-10"
                        value={registerForm.confirmPassword}
                        onChange={(e) => setRegisterForm({...registerForm, confirmPassword: e.target.value})}
                        required
                      />
                    </div>
                  </div>
                  
                  <div className="space-y-2">
                    <Label htmlFor="verification-code">邮箱验证码</Label>
                    <div className="flex space-x-2">
                      <Input
                        id="verification-code"
                        type="text"
                        placeholder="请输入验证码"
                        value={verificationCode}
                        onChange={(e) => setVerificationCode(e.target.value)}
                        required
                      />
                      <Button
                        type="button"
                        variant="outline"
                        onClick={handleGetVerificationCode}
                        disabled={isGettingCode || !registerForm.email}
                        className="whitespace-nowrap"
                      >
                        {isGettingCode ? "发送中..." : "获取验证码"}
                      </Button>
                    </div>
                  </div>
                  
                  <Button 
                    type="submit" 
                    className="w-full bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800"
                    disabled={isLoading}
                  >
                    {isLoading ? "注册中..." : "注册"}
                  </Button>
                </form>
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>
        
        <div className="text-center mt-6 text-sm text-gray-600">
          <p>
            继续使用即表示您同意我们的
            <Button variant="link" className="px-1 text-sm h-auto">服务条款</Button>
            和
            <Button variant="link" className="px-1 text-sm h-auto">隐私政策</Button>
          </p>
        </div>
      </div>
    </div>
  )
}